<script lang="ts">
import type { TColumn } from '~/components/table';
import type { TPresetBreakpoints } from '~/composables/useElementBreakpoint';
import { useUrlSearchParams } from '@peng_kai/kit/libs/vueuse';
import { RangeMonth } from '~/components-business/range';
import { CurrencySelect } from '~/components/currency';
import { useTransportable } from '~/composables/useTransportable';

const active = ref();
const params = useUrlSearchParams('history');
const displayUtc = ref(true);
const referralTypes = computed(() => [
  { value: 4, label: $t('z8E4ejnK0EmiXvDg4BpR0') },
  { value: 13, label: $t('rdt2qztw39rxNJbhu3j4H') },
  { value: 30, label: $t('Ut5xpCDX86xYHSh7PpRj') },
]);
const bonusesTypes = computed(() => [
  { value: 5, label: $t('6wer5H4JBjD0_2ZrC3tj') },
  { value: 10, label: $t('sIuZ756ceX0JfxXeIOy') },
  { value: 11, label: $t('v7FZhX4Rp7gBDgtMbTu6m') },
  { value: 12, label: $t('fwz1nYhgWu5hFswQbyHu') },
  { value: 16, label: $t('wKw15BVopgahUdN_5NKw0') },
  { value: 21, label: $t('pisC94cov4bwZU2uErmo') },
  { value: 22, label: $t('1p1cTdk3dXj73z7Q2yY4m') },
  { value: 23, label: $t('mChzG9TtAtga_8_5sZAcr') },
  { value: 24, label: $t('p3mtpFphdjzqZsM4YEmQm') },
  { value: 25, label: $t('byaG4W1osAFspytjbLrWn') },
  { value: 26, label: $t('bQqCgs7P5pizWmW2fc5zx') },
  { value: 27, label: $t('ab0ucrQKsjeA83oLt3uO') },
  { value: 28, label: $t('id43KeoGedg0wDtwJA2a') },
  { value: 29, label: $t('9YDgNfp42fuZrPsT23jP7') },
  { value: 30, label: $t('3XrsIlm7rf5e6dVcOlWl') },
]);
const commonTypes = computed(() => [
  ...referralTypes.value,
  ...bonusesTypes.value,
  { value: 1, label: 'Manual' },
  { value: 2, label: $t('xQp2HJedTncmCsXifzn3') },
  { value: 3, label: 'Withdraw Go Back' },
  { value: 6, label: $t('p9zKloGqNTkIgC4asiQrx') },
  { value: 7, label: $t('bUsnDrIeEyr9MDa1MFyMm') },
  { value: 8, label: 'Game Reward' },
  { value: 9, label: $t('vwIm7RlsltxuHa5JwVxcO') },
  { value: 14, label: 'Bet Go Back' },
].sort((item1, item2) => Number(item1.value) - Number(item2.value)),
);
</script>

<script setup lang="ts">
const props = withDefaults(defineProps<{
  typeName: string;
  place?: 'modal' | 'page';
}>(), {
  place: 'page',
});
const actions = computed(() => {
  switch (props.typeName) {
    case 'Cashback':
      return [];
      break;
    case 'Bonuses':
      return bonusesTypes.value;
      break;
    case 'Referral':
      return referralTypes.value;
      break;
    // 避免调用时提示可能等于undefined
    default :
      return commonTypes.value;
      break;
  }
});
const [setEle, eleBp] = useElementBreakpoint({});
const transportable = useTransportable();

function useTableList(bp: Ref<TPresetBreakpoints>) {
  const [listQry, listParams] = useFilterPaginationQuery(apis.apiUserFundTransactions, {
    action: { value: props.typeName, responsive: true },
    currency: { value: undefined, responsive: true },
    start_time: {
      value: dayjs().startOf('month').utc(true).valueOf(),
      responsive: true,
    },
    end_time: {
      value: dayjs().endOf('month').utc(true).valueOf(),
      responsive: true,
    },
    type: { value: undefined, responsive: true },
  });
  const listData = computed(() => listQry?.data?.value?.list ?? []);

  const tableBp = computed(() => ({
    s1: bp.value.ltxl,
    s2: bp.value.xl && bp.value.lt4xl,
    s3: bp.value['4xl'],
  }));

  const tableColumn = computed(() => {
    const bp = tableBp.value;
    const columns: TColumn[] = [
      { key: 'time', name: '' },
      { key: 'type', name: $t('dDwMcl9AyHeoBsLwpBgRt'), show: bp.s2 || bp.s3 },
      { key: 'amount', name: $t('plHorg6dj8ZgRdr4b24gt'), thClass: 'text-right', tdClass: 'text-right' },
    ];
    return columns;
  });

  return {
    listData,
    listParams,
    listQry,
    tableBp,
    tableColumn,
  };
}

const { listData, listQry, listParams, tableBp, tableColumn } = useTableList(eleBp);

function onChange(item: any) {
  if (item === 0) {
    listParams.type = undefined;
  }
  else {
    listParams.type = item;
  }
}

watchEffect(() => {
  if (params && params.type) {
    listParams.type = Number(params.type);
    const index = toValue(actions).findIndex(i => i.value === Number(params.type));
    if (index === -1)
      return;
    active.value = toValue(actions)[index].value;
    onChange(toValue(actions)[index].value);
  }
});
</script>

<template>
  <div>
    <div :ref="setEle">
      <Teleport v-if="transportable" to=".transctions .table-filter" :disabled="props.place === 'modal'">
        <div class="gap-2 text-center" :class="{ 'flex ml-auto': eleBp['3xl'], 'grid grid-cols-2 w-full': eleBp.lt3xl, 'mb-2': props.place === 'modal' }">
          <CurrencySelect
            v-model:value="listParams.currency"
            class="antd-cover__Select-3d-gray" :class="{ 'ml-auto w-35': eleBp['3xl'] }"
            size="small" labelAlign="center" allowClear :bordered="false" :placeholder="$t('uIkputJyPtyBCeeSwh2ig')"
          />
          <TAntdTheme v-if="props.typeName !== 'Cashback'" component="Select" theme="light">
            <ASelect
              v-model:value="active" class="antd-cover__Select-3d-gray min-w-30" :options="actions" :bordered="false"
              size="small" :placeholder="$t('ufcZwcQsF8cdsOzyaZc')" :virtual="false" allowClear @change="onChange"
            />
          </TAntdTheme>
          <RangeMonth
            v-model:startTime="listParams.start_time"
            v-model:endTime="listParams.end_time" :bordered="false"
            size="small" :virtual="false" :class="{ 'w-40': eleBp['3xl'] }"
          />
        </div>
      </Teleport>

      <TSuspenseView v-bind="buildSvPropsOfQuery(listQry)" errorClass="min-h-40" outRender>
        <TTable indexId="uid" :columns="tableColumn" :data="listData">
          <template #time-th>
            <TDateFormatTh v-model:utc="displayUtc" />
          </template>

          <template #time-td="{ row }">
            <div v-if="!tableBp.s3" class="text-sys-text-body">
              {{ commonTypes?.filter(i => i.value === row?.type)[0].label }}
            </div>
            <div class="text-sys-text-body">
              {{ $d(row?.create_time, displayUtc ? 'full-utc' : 'full') }}
            </div>
          </template>
          <template #type-td="{ row }">
            <div class="text-sys-text-body">
              {{ commonTypes?.filter(i => i.value === row?.type)[0].label }}
            </div>
          </template>
          <template #amount-td="{ row }">
            <TAmount
              class="text-green-500"
              :class="{ '!text-white': row.amount.indexOf('-') > -1 || row.amount === '0' }"
              showPos
              :value="row.amount"
              :symbol="row?.currency?.currency"
              iconPos="right"
              colored="inherit"
              format="pad-dec"
            />
          </template>
        </TTable>

        <template #pending>
          <div v-if="eleBp.lt4xl">
            <TSkeleton v-for="i in 3" :key="i" class="grid grid-cols-2 mb-8 w-full gap-2">
              <TSkeleton type="rect" width="120px" height="15px" class="col-span-full" />
              <TSkeleton type="rect" height="15px" />
              <TSkeleton type="rect" height="15px" />
            </TSkeleton>
          </div>
          <TTableLoading v-if="eleBp['4xl']" />
        </template>
      </TSuspenseView>
    </div>

    <TPagination
      v-model:page="listParams.page" v-model:pageSize="listParams.page_size" :querier="listQry"
      class="mt-2"
    />
  </div>
</template>
